package com.youlu.campus.service.ad.impl;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.entity.AdsInfo;
import com.youlu.campus.entity.VO.req.AdsInfoQueryVO;
import com.youlu.campus.service.ad.AdsInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class AdsInfoServiceImpl implements AdsInfoService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Page<AdsInfo> list(AdsInfoQueryVO req) {
        log.info(":>>> 开始获取广告信息:{}", JSON.toJSONString(req));
        if (Objects.isNull(req)) {
            log.error(":>>> 获取广告信息错误:参数为空");
            req = new AdsInfoQueryVO();
            req.setPage(1);
            req.setPageSize(10);
        }
        Query query = new Query();
        if (Objects.nonNull(req.getStatus())) {
            query.addCriteria(Criteria.where("status").is(req.getStatus()));
        }
        if (StringUtils.isNotBlank(req.getAppId())) {
            query.addCriteria(Criteria.where("appId").is(req.getAppId()));
        }
        Long count = mongoTemplate.count(query, AdsInfo.class);
        PageRequest pageRequest = PageRequest.of(req.getPage() - 1, req.getPageSize());
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<AdsInfo> infos = mongoTemplate.find(query.with(pageRequest), AdsInfo.class);
        return PageableExecutionUtils.getPage(infos, pageRequest, () -> count);
    }

    @Override
    public AdsInfo find(@NotNull String platform, @NotNull String appId, @NotNull String adId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("adId").is(adId).and("appId").is(appId).and("platform").is(platform));
        return mongoTemplate.findOne(query, AdsInfo.class);
    }
}
